<script>
import { defineComponent, ref, computed } from 'vue';
import FanButton from '../button/button.vue';
import FanContactPanel from '../contact-panel/contact-panel.vue';
import FanPopup from '../popup/popup.vue';
import { createNamespace, transformStyleSize } from '../utils';
import { Config } from '../config';

/**
 * 联系客服按钮
 * 执行顺序：url -> phone -> picture -> { 小程序: 客服按钮, H5: commonConfig 的客服 }
 */
export default defineComponent({
  name: createNamespace('ContactButton')[0],
  options: {
    // https://uniapp.dcloud.io/matter.html#mp
    virtualHost: true,
  },
  emits: ['click'],
  components: { FanButton, FanContactPanel, FanPopup },
  props: {
    customStyle: [Object, String],
    // 优先级最高
    phone: String,
    picture: String,
    time: String,
    timeStyle: String,
    url: String,
    // 小程序客服按钮配置 {}
    mpContact: {
      type: Object,
      default: () => ({}),
    },
    /**
     * 是否以绝对定位撑满父盒子，可以作为遮罩mask使用
     */
    full: {
      type: Boolean,
      default: false,
    },
  },
  setup(props, { emit }) {
    const useMpContact = computed(() => {
      const { phone, picture, url } = props;
      const { runEnv, mpPlugin } = Config;
      return !url && !phone && !picture && runEnv === 'mp' && !mpPlugin;
    });
    const theStyle = computed(() => transformStyleSize(props.customStyle));
    const showPop = ref(false);
    const onClick = () => {
      if (props.url) {
        emit('click', props.url)
        return;
      }
      showPop.value = true;
    };

    return { theStyle, useMpContact, showPop, onClick };
  },
});
</script>

<template>
  <button v-if="useMpContact" class="fan-contact-btn" :class="{ 'fan-contact-btn--full': full }" :style="theStyle"
    open-type="contact" :show-message-card="!!mpContact.img" :send-message-title="mpContact.title"
    :send-message-path="mpContact.path" :send-message-img="mpContact.img">
    <slot />
  </button>
  <template v-else>
    <div class="fan-contact-btn" :class="{ 'fan-contact-btn--full': full }" :style="theStyle" @click="onClick">
      <slot />
    </div>

    <FanPopup v-model:show="showPop" title="客服联系方式" round :custom-style="{ width: '82%' }">
      <div class="fan-hairline--top fan-hairline--bottom" style="padding: 24px 12px 30px">
        <FanContactPanel :phone="phone" :picture="picture" :time="time" :time-style="timeStyle"
          background="var(--fan-primary-color-1)" />
      </div>
      <FanButton block plain :border="false" text-size="16px" @click="showPop = false">关闭</FanButton>
    </FanPopup>
  </template>
</template>

<style lang="less">
.fan-contact-btn {
  padding: 0;
  margin: 0;
  background: transparent;
  border: 0;
  border-radius: 0;
  outline: none;
  font-size: inherit;
  line-height: inherit;
  color: inherit;

  &::after {
    display: none;
  }

  &--full {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    z-index: 1;
  }
}
</style>
